<?php

namespace app\common\model;


class AuthRule extends BaseModel
{
    protected $autoWriteTimestamp = 'datetime';

    public function rules()
    {
        return $this->hasMany(AuthRule::class, 'pid', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(AuthRule::class, 'pid', 'id');
    }

    /**
     * 通过规则名称获取根节点
     * @param string $name 规则名称
     * @return AuthRule|null
     * @date 2020/09/15
     * @author longli
     */
    public static function getRootRuleByName($name)
    {
        $rule = static::get(['name' => $name]);
        if(empty($rule) || !$rule->pid) return $rule;
        while($rule->pid) $rule = $rule->parent;
        return $rule;
    }
}
